package com.java.tutorials.spring.ApplicationContext;

import com.java.tutorials.spring.SpringTesterBase;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

/**
 * Created by xuzhike on 2016/1/28.
 * http://www.java2s.com/Code/Java/Spring/ContextApplicationEvent.htm
 */
public class ContextApplicationEventDemo extends SpringTesterBase {
    @Test
    public void testContextApplicationEvent(){
        EventPublisherDemo pub = (EventPublisherDemo) ctx.getBean("publisher");
        pub.report("A");
        pub.report("B");
    }
}

class EventPublisherDemo implements ApplicationContextAware {


    private ApplicationContext ctx;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
        SpringTesterBase.printMsg("setApplicationContext");

    }

    public void report(String message) {
        SpringTesterBase.printMsg("--------report");
        ctx.publishEvent(new MessageEvent(this, message));
    }

}

class MessageEvent extends ApplicationEvent {
    private String message;

    public MessageEvent(Object source, String message) {
        super(source);
        SpringTesterBase.printMsg("MessageEvent");
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

class MessageEventListener implements ApplicationListener {
    public void onApplicationEvent(ApplicationEvent event) {
        SpringTesterBase.printMsg("onApplicationEvent");
        if (event instanceof MessageEvent) {
            MessageEvent messageEvent = (MessageEvent) event;
            System.out.println("Received " + messageEvent.getMessage());
        }
    }
}